package com.bsoft.gol.hcs.specialist.service.impl;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.common.bean.request.DecryptDataReq;
import com.bsoft.gol.hcs.specialist.entity.PatientSearchResult;
import ctd.account.UserRoleToken;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.AppContextHolder;
import ctd.util.annotation.RpcService;
import hcn.base.Dept;
import hcn.base.Organization;
import hcn.service.accessAuth.AccessAuthService;
import hcn.service.accessAuth.request.CancelAuthRequest;
import hcn.service.accessAuth.request.InitiativeAuthRequest;
import hcn.service.base.IOrgDoctorsService;
import hcn.util.BaseResponse;
import hcn.bean.UserAllVo;
import hcn.bean.specialist.qo.GroupMemberRequest;
import hcn.bean.specialist.vo.ChronicTeamList;
import hcn.bean.specialist.vo.QueryChronicDoctorListResponse;
import hcn.bean.specialist.vo.QueryDoctorDepartmentListResponse;
import hcn.docteam.DocTeamMemberEntity;
import hcn.protocol.ods.card.PersonInfoVo;
import hcn.specialist.DiseaseSpecies;
import hcn.specialist.FusGroupChronicRecordExtendProperty;
import com.bsoft.gol.hcs.his.service.SendMsgService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.atag.util.bbp.RoleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import pcn.service.DocIdentityService;
import pcn.service.web.BaseDeviceService;
import service.rpc.*;
import service.rpc.impl.CardManageServiceImpl;
import com.bsoft.gol.hcs.specialist.bean.request.OutPatientAddGroupRequest;
import com.bsoft.gol.hcs.specialist.bean.request.SaveGroupRequest;
import com.bsoft.gol.hcs.specialist.bean.response.*;
import com.bsoft.gol.hcs.specialist.dao.*;
import com.bsoft.gol.hcs.specialist.entity.DiseaseExtendPropertyEntity;
import com.bsoft.gol.hcs.specialist.entity.FusHealthEducationRelation;
import com.bsoft.gol.hcs.specialist.entity.FusTeamChronicGroupRecordEntity;
import com.bsoft.gol.hcs.specialist.service.IFollowUpPlanService;
import com.bsoft.gol.hcs.specialist.service.IFusHealthEducationService;
import com.bsoft.gol.hcs.specialist.service.TeamChronicGroupService;
import com.bsoft.gol.hcs.utils.*;
import ssdev.bbp.person.IPersonService;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 入组
 *
 * @author lxy
 * @date 2020/7/18
 */
@SsdevService("teamChronicGroup")
public class TeamChronicGroupServiceImpl implements TeamChronicGroupService {

    private static final Logger logger = LoggerFactory.getLogger(TeamChronicGroupServiceImpl.class);

    @Autowired
    private FusTeamChronicGroupRecordDAO fusTeamChronicGroupRecordDAO;
    @Autowired
    private DiseaseSpeciesDAO diseaseSpeciesDAO;
    @Autowired
    private DiseaseExtendPropertyDAO diseaseExtendPropertyDAO;
    @Autowired
    private GroupRecordExtendPropertyDAO groupRecordExtendPropertyDAO;
    @Autowired
    private IDocTeamMemberRpcService docTeamMemberRpcService;
    @Autowired
    private IDocTeamRpcService docTeamRpcService;
    @Resource(name = "followUpPlanService")
    private IFollowUpPlanService followUpPlanService;
    @Autowired
    private SendMsgService sendMsgService;
    @Autowired
    private IFusHealthEducationService fusHealthEducationService;
    @Autowired
    private IOrganizationRpcService organizationRpcService;
    @Autowired
    private IDeptMainRpcService deptMainRpcService;
    @Autowired
    private CardManageServiceImpl cardManageService;
    @Autowired
    private DoctorInfoServiceIntf doctorInfoServiceIntf;
    @Autowired
    private IBaseUserService userService;
    @SsdevReference("hcn.baseDeviceService")
    private BaseDeviceService baseDeviceService;
    @Autowired
    private DocTeamDiseaseDAO docTeamDiseaseDAO;
    @Autowired
    private FollowUpRecordsDAO followUpRecordsDAO;
    @Autowired
    private PatientSearchResultDAO patientSearchResultDAO;
    @SsdevReference("hcb.accessAuth")
    private AccessAuthService accessAuthService;
    @SsdevReference("hcn.orgDoctorsService")
    private IOrgDoctorsService orgDoctorsService;

    @SsdevReference("hcn.docIdentityService")
    private DocIdentityService docIdentityService;

    /**
     * 添加入组
     *
     * @param request req
     * @return res
     */
    @Override
    @RpcService
    public List<FusTeamChronicGroupRecordEntity> saveTeamMember(SaveGroupRequest request) throws ControllerException {
        logger.info("saveTeamMember request:{}", JSON.toJSONString(request));
        if (CommonUtils.isEmpty(request.getList())) {
            throw new ControllerException("入组的");
        }
        if (CommonUtils.isNotEmpty(request.getList())) {
            for (GroupMemberRequest request1 : request.getList()) {
                if (!StringUtils.isNoneEmpty(request1.getPersonId(), request1.getMedicalTeamId() + "", request1.getChronicDiseaseId() + "")) {
                    throw new ControllerException("参数错误");
                }
                if (CommonUtils.isEmpty(request1.getPatientId())) {
                    throw new ControllerException(request1.getPersonName() + "就诊卡信息为空无法添加入组");
                }
            }

            for (GroupMemberRequest request1 : request.getList()) {
                DiseaseSpecies diseaseSpecies = diseaseSpeciesDAO.getDiseaseTypeDetail(request1.getChronicDiseaseId());
                if (diseaseSpecies == null) {
                    throw new ControllerException("病种不存在");
                }
                Organization organization = organizationRpcService.getOrgDetailByOrgCode(request1.getOrganizationId());
                if (organization == null) {
                    throw new ControllerException("机构不存在");
                }

                Dept dept = deptMainRpcService.getDeptByLocalDeptId(organization.getOrgId(), diseaseSpecies.getDepartmentId());
                if (dept == null) {
                    throw new ControllerException("科室不存在");
                }
                request1.setOrganizationName(organization.getFullName());
                request1.setDepartmentId(dept.getDeptId());
                request1.setDepartmentId(dept.getLocalDeptId());
                request1.setDepartmentName(dept.getName());
                FusTeamChronicGroupRecordEntity recordEntity = fusTeamChronicGroupRecordDAO.getGroupRecordByTeamIdAndDiseaseId(request1.getPersonId(),
                        request1.getMedicalTeamId(), request1.getChronicDiseaseId());
                if (CommonUtils.isNotEmpty(recordEntity)) {
                    throw new ControllerException("此病种已入组或入组确认中");
                }
            }

            for (GroupMemberRequest request1 : request.getList()) {
                FusTeamChronicGroupRecordEntity entity = new FusTeamChronicGroupRecordEntity();
                BeanUtils.copyProperties(request1, entity);
                // 医生添加不需要审核， 但需要患者确认
                entity.setApplyStatus("0");
                entity.setApplyType("2");
                entity.setProtocolStatus("0");
                entity.setApplyTime(new Date());
                entity.setAuditTime(new Date());
                entity.setAuditPersonName(request1.getDoctorName());
                entity.setAuditPersonId(request1.getDocId());
                entity.setApplyPersonId(request1.getDocId());
                entity.setApplyPersonName(request1.getDoctorName());
                setOrgIdAndDeptId(entity);
                fusTeamChronicGroupRecordDAO.save(entity);
                //保存扩展属性信息
                if (CommonUtils.isNotEmpty(request1) && CommonUtils.isNotEmpty(request1.getExtendList())) {
                    for (FusGroupChronicRecordExtendProperty fusProperty : request1.getExtendList()) {
                        fusProperty.setOrganizationId(request1.getOrganizationId());
                        fusProperty.setDiseaseTypeId(request1.getChronicDiseaseId());
                        fusProperty.setTeamChronicGroupId(entity.getTeamChronicGroupId());
                        fusProperty.setExtendTime(new Date());
                        fusProperty.setCreateTime(new Date());
                        groupRecordExtendPropertyDAO.save(fusProperty);
                    }
                }
                try {
                    //主动授权
                    UserRoleToken current = UserRoleToken.getCurrent();
                    InitiativeAuthRequest request2 = new InitiativeAuthRequest();
                    request2.setTenantId(current.getTenantId());
                    request2.setOrgId(current.getOrgId());
                    request2.setMpiId(entity.getPersonId());
                    request2.setResourceType("0");
                    request2.setBizId(String.valueOf(entity.getTeamChronicGroupId()));
                    request2.setBizType("1");
                    request2.setAuthType("1");
                    request2.setAuthExpireTime(new Date());
                    request2.setApplyId(entity.getPersonId());
                    request2.setApplyName(entity.getPersonName());
                    accessAuthService.initiativeAuth(request2);
                } catch (Exception e) {
                    logger.error("保存用户主动授权数据失败", e);
                }
                if (request1.isSendSMS()) {
                    // TODO 发送短信给患者
                    try {
                        sendMsgService.sendMessage(JSONObject.toJSON(entity), true, 3);
                    } catch (Exception e) {
                        throw new ControllerException("短信发送失败");
                    }
                }
            }
        }
        return new ArrayList<>();
    }


    /**
     * @description: 初始化历史数据，没啥用
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/11/3 14:34
     * @param:
     * @return: void
     */
    @RpcService
    public void init() {
        List<FusTeamChronicGroupRecordEntity> fusTeamChronicGroupRecordEntities = fusTeamChronicGroupRecordDAO.queryAll();
        if (CommonUtils.isNotEmpty(fusTeamChronicGroupRecordEntities)) {
            for (FusTeamChronicGroupRecordEntity fusTeamChronicGroupRecordEntity : fusTeamChronicGroupRecordEntities) {
                setOrgIdAndDeptId(fusTeamChronicGroupRecordEntity);
                fusTeamChronicGroupRecordDAO.update(fusTeamChronicGroupRecordEntity);
            }
        }
    }

    /**
     * @description: 机构id和科室id赋值
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/11/3 14:32
     * @param: fusTeamChronicGroupRecordEntity
     * @return: void
     */
    private void setOrgIdAndDeptId(FusTeamChronicGroupRecordEntity fusTeamChronicGroupRecordEntity) {
        Organization orgDetailByOrgCode = organizationRpcService.getOrgDetailByOrgCode(fusTeamChronicGroupRecordEntity.getOrganizationId());
        if (null != orgDetailByOrgCode) {
            fusTeamChronicGroupRecordEntity.setOrgId(orgDetailByOrgCode.getOrgId());
            Dept deptByLocalDeptId = deptMainRpcService.getDeptByLocalDeptId(orgDetailByOrgCode.getOrgId(), fusTeamChronicGroupRecordEntity.getDepartmentId());
            if (null != deptByLocalDeptId) {
                fusTeamChronicGroupRecordEntity.setDeptId(deptByLocalDeptId.getDeptId());
            }
        }
    }

    @Override
    @RpcService
    public void outTeamMember(GroupMemberRequest request) throws ControllerException {
        BaseResponse response = new BaseResponse();
        if (CommonUtils.isEmpty(request.getTeamChronicGroupId()) ||
                CommonUtils.isEmpty(request.getOutPersonId())) {
            throw new ControllerException("参数为空");
        }
        FusTeamChronicGroupRecordEntity recordEntity = fusTeamChronicGroupRecordDAO.get(request.getTeamChronicGroupId());

        if (recordEntity == null || !"1".equals(recordEntity.getApplyStatus())) {
            throw new ControllerException("该患者未入组");
        }
        recordEntity.setApplyStatus("3");
        recordEntity.setOutPersonId(request.getOutPersonId());
        recordEntity.setAuditOpinion(request.getAuditOpinion());
        recordEntity.setOutPersonName(request.getOutPersonName());
        recordEntity.setOutTime(new Date());
        fusTeamChronicGroupRecordDAO.update(recordEntity);
        ThreadPoolExecutorUtil.getThreadPoolExecutor().execute(
                () -> {
                    //自动终止随访计划
                    try {
                        followUpPlanService.autoStopExecutionList();
                    } catch (ControllerException e) {
                        e.printStackTrace();
//                        throw new ControllerException("搜索规则名称已存在");
                    }
                }
        );
        ThreadPoolExecutorUtil.getThreadPoolExecutor().execute(
                () -> {
                    //移除主动授权数据
                    try {
                        CancelAuthRequest req = new CancelAuthRequest();
                        req.setMpiId(recordEntity.getPersonId());
                        req.setBizId(String.valueOf(recordEntity.getTeamChronicGroupId()));
                        req.setBizType("1");
                        accessAuthService.cancelAuth(req);
                    } catch (Exception e) {
                        logger.error("患者出组时移除主动授权记录失败", e);
                    }
                }
        );
        return;
    }

    @Override
    @RpcService
    public void auditTeamGroup(GroupMemberRequest request) throws ControllerException {
        BaseResponse response = new BaseResponse();
        if (CommonUtils.isEmpty(request.getAuditPersonId()) ||
                CommonUtils.isEmpty(request.getTeamChronicGroupId()) ||
                CommonUtils.isEmpty(request.getAuditPersonName()) ||
                CommonUtils.isEmpty(request.getApplyStatus())) {
            throw new ControllerException("缺少参数");
        }
        // 审核不通过
        if ("2".equals(request.getApplyStatus())) {
            FusTeamChronicGroupRecordEntity entity = fusTeamChronicGroupRecordDAO.get(request.getTeamChronicGroupId());
            if (entity != null) {
                entity.setApplyStatus(request.getApplyStatus());
                entity.setAuditPersonId(request.getAuditPersonId());
                entity.setAuditOpinion(request.getAuditOpinion());
                entity.setAuditPersonName(request.getAuditPersonName());
                entity.setAuditTime(new Date());
                entity = fusTeamChronicGroupRecordDAO.update(entity);
                //todo 审核不通过推送
                try {
                    sendMsgService.sendMessage(JSONObject.toJSON(entity), false, 1);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ControllerException("推送消息失败" + e.getMessage());
                }
            } else {
                throw new ControllerException("审核记录不存在");
            }
        }
        // 审核通过
        if ("1".equals(request.getApplyStatus())) {
            FusTeamChronicGroupRecordEntity entity = fusTeamChronicGroupRecordDAO.get(request.getTeamChronicGroupId());
            if (entity != null) {
                if (CommonUtils.isNotEmpty(request.getMedicalTeamId()) &&
                        CommonUtils.isNotEmpty(request.getChronicDiseaseId())) {
                    FusTeamChronicGroupRecordEntity recordEntity = fusTeamChronicGroupRecordDAO.getGroupRecordByTeamIdAndDiseaseId(entity.getPersonId(), request.getMedicalTeamId(), request
                            .getChronicDiseaseId());
                    if (recordEntity != null && "1".equals(recordEntity.getApplyStatus())) {
                        throw new ControllerException("该患者已经加入该组");
                    }
                }
                entity.setApplyStatus(request.getApplyStatus());
                entity.setAuditPersonId(request.getAuditPersonId());
                entity.setAuditPersonName(request.getAuditPersonName());
                entity.setAuditTime(new Date());
                if (request.getDoctorId() != null) {
                    entity.setDoctorId(request.getDoctorId());
                }
                if (request.getDoctorName() != null) {
                    entity.setDoctorName(request.getDoctorName());
                }

                if (request.getMedicalTeamId() != null) {
                    entity.setMedicalTeamId(request.getMedicalTeamId());
                }
                if (request.getMedicalTeamName() != null) {
                    entity.setMedicalTeamName(request.getMedicalTeamName());
                }

                if (request.getChronicDiseaseId() != null) {
                    entity.setChronicDiseaseId(request.getChronicDiseaseId());
                }
                if (request.getChronicDiseaseName() != null) {
                    entity.setChronicDiseaseName(request.getChronicDiseaseName());
                }
                if (CommonUtils.isNotEmpty(request.getDepartmentId())) {
                    entity.setDepartmentId(request.getDepartmentId());
                }
                if (CommonUtils.isNotEmpty(request.getDepartmentName())) {
                    entity.setDepartmentName(request.getDepartmentName());
                }
                fusTeamChronicGroupRecordDAO.update(entity);
                //保存扩展属性信息
                if (CommonUtils.isNotEmpty(request.getExtendList())) {
                    for (FusGroupChronicRecordExtendProperty fusProperty : request.getExtendList()) {
                        fusProperty.setOrganizationId(entity.getOrganizationId());
                        fusProperty.setDiseaseTypeId(request.getChronicDiseaseId());
                        fusProperty.setTeamChronicGroupId(request.getTeamChronicGroupId());
                        fusProperty.setExtendTime(new Date());
                        fusProperty.setCreateTime(new Date());
                        groupRecordExtendPropertyDAO.save(fusProperty);
                    }
                }

                try {
                    //主动授权
                    UserRoleToken current = UserRoleToken.getCurrent();
                    InitiativeAuthRequest request1 = new InitiativeAuthRequest();
                    request1.setTenantId(current.getTenantId());
                    request1.setOrgId(current.getOrgId());
                    request1.setMpiId(entity.getPersonId());
                    request1.setResourceType("0");
                    request1.setBizId(String.valueOf(entity.getTeamChronicGroupId()));
                    request1.setBizType("1");
                    request1.setAuthType("1");
                    request1.setAuthExpireTime(new Date());
                    request1.setApplyId(entity.getPersonId());
                    request1.setApplyName(entity.getPersonName());
                    accessAuthService.initiativeAuth(request1);
                } catch (Exception e) {
                    logger.error("保存用户主动授权数据失败", e);
                }

                try {
                    sendMsgService.sendMessage(JSONObject.toJSON(entity), true, 1);
                    if (request.isSendSMS()) {
                        sendMsgService.sendMessage(JSONObject.toJSON(entity), true, 3);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ControllerException("推送消息失败:" + e.getMessage());
                }

            } else {
                throw new ControllerException("审核记录不存在");
            }
        }
        return;
    }

    @Override
    @RpcService
    public AuditGroupListResponse auditGroupList(GroupMemberRequest request) throws ControllerException {

        AuditGroupListResponse response = new AuditGroupListResponse();
        HashMap<String, String> doctorCodeMap = new HashMap<>();
        //先不区分院内和院外
        // request.setApplyType("1");
        if (StringUtils.isNotEmpty(request.getProtocolSetStatus()) && StringUtils.isNotEmpty(request.getDoctorId())) {
            //患者确认 查询
            List<Long> docTeamIds = docTeamMemberRpcService.findMedicalTeamIdList(request.getDoctorId());
            if (CommonUtils.isNotEmpty(docTeamIds)) {
                List<String> chronicDiseaseIds = docTeamDiseaseDAO.findChronicDiseaseId(docTeamIds);
                request.setChronicDiseaseIdList(chronicDiseaseIds);
            }
        }

        List<TeamChronicGroupResponse> list = fusTeamChronicGroupRecordDAO.auditGroupList(request);
        if (CommonUtils.isNotEmpty(list)) {
            for (TeamChronicGroupResponse teamChronicGroupResponse : list) {
                teamChronicGroupResponse.setAge((byte) IdcardUtil.getAge(teamChronicGroupResponse.getCardNumber()));
                if (StringUtils.isNotEmpty(doctorCodeMap.get(teamChronicGroupResponse.getApplyPersonId()))){
                    teamChronicGroupResponse.setApplyPersonCode(doctorCodeMap.get(teamChronicGroupResponse.getApplyPersonId()));
                }else {
                    String doctorUserId = docIdentityService.getDoctorUserId(teamChronicGroupResponse.getApplyPersonId());
                    //用doctorUserId拿到personInfo，根据personInfo中的字典值cd拿到医生编码
                    Map<String, Object> personInfo = AppContextHolder.get().getBean(IPersonService.class).getByUserId(doctorUserId);
                    if (CommonUtils.isNotEmpty(personInfo)) {
                        teamChronicGroupResponse.setApplyPersonCode((String) personInfo.get("cd"));
                        doctorCodeMap.put(teamChronicGroupResponse.getApplyPersonId(), (String) personInfo.get("cd"));
                    }
                }
                if(StringUtils.isNotEmpty(doctorCodeMap.get(teamChronicGroupResponse.getDocId()))){
                    teamChronicGroupResponse.setDoctorId(doctorCodeMap.get(teamChronicGroupResponse.getDocId()));
                }else{
                    String docUserId = docIdentityService.getDoctorUserId(teamChronicGroupResponse.getDocId());
                    //用docUserId拿到personInfo，根据personInfo中的字典值cd拿到医生编码
                    Map<String, Object> perInfo = AppContextHolder.get().getBean(IPersonService.class).getByUserId(docUserId);
                    if (CommonUtils.isNotEmpty(perInfo)) {
                        teamChronicGroupResponse.setDoctorId((String) perInfo.get("cd"));
                        doctorCodeMap.put(teamChronicGroupResponse.getDocId(), (String) perInfo.get("cd"));
                    }
                }

            }
        }
        Long total = fusTeamChronicGroupRecordDAO.auditGroupListCount(request);
        response.setList(list);
        response.setTotal(total);
        return response;
    }

    @Override
    @RpcService
    public AuditGroupListResponse personGroupList(GroupMemberRequest request) throws ControllerException {
        if (CommonUtils.isEmpty(request.getDocId()) && CommonUtils.isEmpty(request.getMedicalTeamId())
                && CommonUtils.isEmpty(request.getChronicDiseaseId())) {
            throw new ControllerException("参数为空");
        }
        AuditGroupListResponse response = new AuditGroupListResponse();
        //request.setApplyStatus("1");
        List<TeamChronicGroupResponse> list = fusTeamChronicGroupRecordDAO.personGroupList(request);
        Long total = 0L;
        if (CommonUtils.isNotEmpty(list)) {
            Long myPersonCount = fusTeamChronicGroupRecordDAO.personGroupListCount(request);
            List<String> personIds = new ArrayList<>();
            for (TeamChronicGroupResponse response1 : list) {
                if (CommonUtils.isEmpty(response1.getAge())) {
                    response1.setAge((byte) IdcardUtil.getAge(response1.getCardNumber()));
                }
                personIds.add(response1.getPersonId());
                //根据personId和docId查询病种信息
                if (CommonUtils.isNotEmpty(response1.getPersonId())) {
                    GroupMemberRequest request1 = new GroupMemberRequest();
                    request1.setPersonId(response1.getPersonId());
                    List<QueryChronicListResponse> queryChronicListResponses = fusTeamChronicGroupRecordDAO.auditGroupMemberListByPersonId(request1);
                    response1.setChronicDiseases(queryChronicListResponses);
                    //处理显示该患者已入组的病种信息，通过，拼接
                    if (CommonUtils.isNotEmpty(queryChronicListResponses)) {
                        String chronicDiseaseIds = "";
                        String chronicDiseaseNames = "";
                        for (QueryChronicListResponse queryChronicList : queryChronicListResponses) {
                            //applyStatus = 1,已入组的病种信息
                            if ("1".equals(queryChronicList.getApplyStatus())) {
                                chronicDiseaseIds = chronicDiseaseIds + queryChronicList.getChronicDiseaseId() + ",";
                                chronicDiseaseNames = chronicDiseaseNames + queryChronicList.getChronicDiseaseName() + ",";
                            }
                        }
                        if (CommonUtils.isNotEmpty(chronicDiseaseIds)) {
                            response1.setChronicDiseaseIds(chronicDiseaseIds.substring(0, chronicDiseaseIds.length() - 1));
                        } else {
                            response1.setChronicDiseaseIds(chronicDiseaseIds);
                        }
                        if (CommonUtils.isNotEmpty(chronicDiseaseNames)) {
                            response1.setChronicDiseaseName(chronicDiseaseNames.substring(0, chronicDiseaseNames.length() - 1));
                        } else {
                            response1.setChronicDiseaseName(chronicDiseaseNames);
                        }
                    }
                }

            }

            if ("1".equals(request.getApplyStatus())) {
                // 查询当日患者待执行随访计划的数量
                List<QueryExecutionCountDto> dto = fusTeamChronicGroupRecordDAO.queryExecutionCountByPatient(request, personIds);
                Map<String, Long> map = new HashMap<>(dto.size());
                if (CommonUtils.isNotEmpty(dto)) {
                    for (QueryExecutionCountDto dto1 : dto) {
                        map.put(dto1.getPersonId(), dto1.getNum());
                    }
                }
                for (TeamChronicGroupResponse response1 : list) {
                    if (map.get(response1.getPersonId()) != null) {
                        response1.setExePlanCount(map.get(response1.getPersonId()));
                    } else {
                        response1.setExePlanCount(0L);
                    }
                }
            }
            List<TeamChronicGroupResponse> newList = list.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TeamChronicGroupResponse::getPersonId))), ArrayList::new));
            response.setList(newList);
            response.setTotal(myPersonCount);
        } else {
            response.setList(null);
            response.setTotal(total);
        }
        return response;
    }

    /*
  1、国籍默认中国， 民族默认汉族——健康城市（必填）

2、当用户属于所选病种的多个团队时，下拉选择所属的团队。例：A团队与B团队都管辖高血压慢病，李医生同时属于A团队与B团队，此时当入组慢病选择高血压时，需要选择所属团队是A团队还是B团队

3、院外患者入组，校验当前患者是否在平台已有账号（姓名+身份+手机号码）：

若无，则为当前患者创建账号，密码默认手机号码后6位，并发送短信给患者（通知模板见：消息推送）
若有，则自动关联已有账号，若手机号码不一致，此处添加的手机号码作为联系电话单独保存，不覆盖原账号
   */
    @Override
    @RpcService
    public void outPatientAddGroup(OutPatientAddGroupRequest request) throws ControllerException {
        if (Constants.GOL.equals(request.getType())) {
            logger.info("进入智慧健康通");
        } else {
            logger.info("进入互联网医院");
//            Account account = accountDAO.getAccountByInfo(request.getPersonName(), request.getTelephone(), request.getCardType(), request.getCardNumber());
//            FusTeamChronicGroupRecordEntity recordEntity;
//            if (account != null) {
//                recordEntity = fusTeamChronicGroupRecordDAO.getGroupRecordByTeamIdAndDiseaseId(String.valueOf(account.getId()), request.getMedicalTeamId(), request
//                        .getChronicDiseaseId());
//                if (recordEntity != null && "1".equals(recordEntity.getApplyStatus())) {
//                    throw new ControllerException("该患者已入组");
//                }
//                recordEntity = new FusTeamChronicGroupRecordEntity();
//                BeanUtils.copyProperties(request, recordEntity);
//                recordEntity.setAge(Byte.valueOf(request.getAge()));
//                recordEntity.setApplyStatus("1");
//                recordEntity.setPersonId(String.valueOf(account.getId()));
//                recordEntity.setApplyType("2");
//                recordEntity.setApplyTime(new Date());
//                recordEntity.setAuditTime(new Date());
//                recordEntity.setApplyPersonId(request.getDocId());
//                recordEntity.setApplyPersonName(request.getDoctorName());
//                recordEntity.setAuditPersonId(request.getDocId());
//                recordEntity.setAuditPersonName(request.getDoctorName());
//                setOrgIdAndDeptId(recordEntity);
//                fusTeamChronicGroupRecordDAO.save(recordEntity);
//            } else {
//                String token = UUID.randomUUID().toString();
//                token = token.replace("-", "");
//                account = new Account();
//                account.setUtype((byte) 1);
//                account.setPassword(MD5Utils.getMD5(request.getTelephone().substring(request.getTelephone().length() - 6)));
//                account.setToken(token);
//                account.setMobile(request.getTelephone());
//                account.setFlag(Byte.valueOf("1"));
//                account.setRegdate(new Timestamp(System.currentTimeMillis()));
//                account.setRegtype(Short.valueOf("1"));
//                Account save = accountDAO.save(account);
//                recordEntity = new FusTeamChronicGroupRecordEntity();
//                BeanUtils.copyProperties(request, recordEntity);
//                recordEntity.setAge(Byte.valueOf(request.getAge()));
//                recordEntity.setApplyStatus("1");
//                recordEntity.setPersonId(String.valueOf(save.getId()));
//                recordEntity.setApplyType("2");
//                recordEntity.setApplyTime(new Date());
//                recordEntity.setAuditTime(new Date());
//                recordEntity.setApplyPersonId(request.getDocId());
//                recordEntity.setApplyPersonName(request.getDoctorName());
//                recordEntity.setAuditPersonId(request.getDocId());
//                recordEntity.setAuditPersonName(request.getDoctorName());
//                setOrgIdAndDeptId(recordEntity);
//                fusTeamChronicGroupRecordDAO.save(recordEntity);
//            }
        }
        return;
    }

    @Override
    @RpcService
    public void modifyTelephone(GroupMemberRequest request) throws ControllerException {
        FusTeamChronicGroupRecordEntity recordEntity = fusTeamChronicGroupRecordDAO.get(request.getTeamChronicGroupId());
        if (recordEntity == null) {
            throw new ControllerException("未查询到该条入组信息");
        }
        recordEntity.setTelephone(request.getTelephone());
        fusTeamChronicGroupRecordDAO.update(recordEntity);
        return;
    }

    @Override
    @RpcService
    public void modifyChronicTeam(GroupMemberRequest request) throws ControllerException {
        logger.info("modifyChronicTeam request:{}", JSON.toJSONString(request));
        if (CommonUtils.isEmpty(request.getTeamChronicGroupId())
                || CommonUtils.isEmpty(request.getMedicalTeamId())
                || CommonUtils.isEmpty(request.getMedicalTeamName())
                || CommonUtils.isEmpty(request.getChronicDiseaseId())
                || CommonUtils.isEmpty(request.getChronicDiseaseName())
                || CommonUtils.isEmpty(request.getDocId())
                || CommonUtils.isEmpty(request.getDoctorId())
                || CommonUtils.isEmpty(request.getDoctorName())) {
            throw new ControllerException("参数为空");
        }
        FusTeamChronicGroupRecordEntity recordEntity =
                fusTeamChronicGroupRecordDAO.get(request.getTeamChronicGroupId());
        if (recordEntity == null) {
            throw new ControllerException("未查询到该条入组信息");
        }
        if (CommonUtils.isNotEmpty(request.getMedicalTeamId()) &&
                CommonUtils.isNotEmpty(request.getChronicDiseaseId())) {
            FusTeamChronicGroupRecordEntity record =
                    fusTeamChronicGroupRecordDAO.getGroupRecordByTeamIdAndDiseaseId(recordEntity.getPersonId(),
                            request.getMedicalTeamId(), request
                                    .getChronicDiseaseId());
            if (record != null && record.getDocId().equals(request.getDocId())) {
                throw new ControllerException("患者已在要变更的组中或者有未审核记录");
            }
        }
        if (CommonUtils.isNotEmpty(request.getMedicalTeamId())) {
            recordEntity.setMedicalTeamId(request.getMedicalTeamId());
        }
        if (CommonUtils.isNotEmpty(request.getMedicalTeamName())) {
            recordEntity.setMedicalTeamName(request.getMedicalTeamName());
        }
        if (CommonUtils.isNotEmpty(request.getChronicDiseaseId())) {
            recordEntity.setChronicDiseaseId(request.getChronicDiseaseId());
        }
        if (CommonUtils.isNotEmpty(request.getChronicDiseaseName())) {
            recordEntity.setChronicDiseaseName(request.getChronicDiseaseName());
        }
        if (CommonUtils.isNotEmpty(request.getDoctorId())) {
            recordEntity.setDoctorId(request.getDoctorId());
        }
        if (CommonUtils.isNotEmpty(request.getDocId())) {
            recordEntity.setDocId(request.getDocId());
        }
        if (CommonUtils.isNotEmpty(request.getDoctorName())) {
            recordEntity.setDoctorName(request.getDoctorName());
        }
        if (CommonUtils.isNotEmpty(request.getDepartmentId())) {
            recordEntity.setDepartmentId(request.getDepartmentId());
        }
        if (CommonUtils.isNotEmpty(request.getDepartmentName())) {
            recordEntity.setDepartmentName(request.getDepartmentName());
        }
        fusTeamChronicGroupRecordDAO.update(recordEntity);
        //更新随访记录
        followUpRecordsDAO.updateDocInfoByGroupId(request.getMedicalTeamId(), request.getMedicalTeamName(),
                request.getChronicDiseaseId(), request.getChronicDiseaseName(), request.getDocId(),
                request.getDoctorId(), request.getDoctorName(), request.getTeamChronicGroupId());
        //先删除对应病种+入组id的扩展参数,然后重新保存
        Long chronicDiseaseId = request.getChronicDiseaseId();
        Long teamChronicGroupId = request.getTeamChronicGroupId();
        groupRecordExtendPropertyDAO.deleteExtendPropertyByDiseaseTypeIdAndTeamChronicGroupId(chronicDiseaseId,
                teamChronicGroupId);
        //保存扩展属性信息
        if (CommonUtils.isNotEmpty(request.getExtendList())) {
            for (FusGroupChronicRecordExtendProperty fusProperty : request.getExtendList()) {
                fusProperty.setOrganizationId(request.getOrganizationId());
                fusProperty.setDiseaseTypeId(request.getChronicDiseaseId());
                fusProperty.setTeamChronicGroupId(request.getTeamChronicGroupId());
                fusProperty.setExtendTime(new Date());
                fusProperty.setCreateTime(new Date());
                groupRecordExtendPropertyDAO.save(fusProperty);
            }
        }
        if (request.isSendSMS()) {
            // TODO 发送短息给患者
            try {
                sendMsgService.sendMessage(JSONObject.toJSON(recordEntity), true, 3);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ControllerException("短信发送失败:" + e.getMessage());
            }
        }
        return;

    }

    @Override
    @RpcService
    public List<TeamChronicGroupForAppResponse> applyGroupList(GroupMemberRequest request) throws ControllerException {
        if (CommonUtils.isEmpty(request.getPersonId()) && CommonUtils.isEmpty(request.getPersonIdList())) {
            throw new ControllerException("审核记录不存在");
        }
        request.setApplyType("1");
        List<TeamChronicGroupResponse> list = fusTeamChronicGroupRecordDAO.auditGroupList(request);
        List<TeamChronicGroupForAppResponse> responses = new ArrayList<>();
        if (CommonUtils.isNotEmpty(list)) {
            for (TeamChronicGroupResponse response1 : list) {
                TeamChronicGroupForAppResponse teamChronicGroupForAppResponse = new TeamChronicGroupForAppResponse();
                BeanUtils.copyProperties(response1, teamChronicGroupForAppResponse);
                responses.add(teamChronicGroupForAppResponse);
            }
        }
        return responses;
    }

    @Override
    @RpcService
    public TeamChronicGroupForAppResponse applyGroupDetail(GroupMemberRequest request) throws ControllerException {
        BaseResponse<TeamChronicGroupForAppResponse> response = new BaseResponse<>();
        if (CommonUtils.isEmpty(request.getTeamChronicGroupId())) {
            throw new ControllerException("参数不能为空");
        }
        FusTeamChronicGroupRecordEntity recordEntity = fusTeamChronicGroupRecordDAO.get(request.getTeamChronicGroupId());
        TeamChronicGroupForAppResponse responses = new TeamChronicGroupForAppResponse();
        BeanUtils.copyProperties(recordEntity, responses);
        return responses;
    }

    @Override
    @RpcService
    public List<ChronicTeamList> queryTeamList(GroupMemberRequest request) throws ControllerException {
        BaseResponse<List<ChronicTeamList>> response = new BaseResponse<>();
        if (CommonUtils.isEmpty(request.getDocId())) {
            throw new ControllerException("参数不能为空");
        }
        if (CommonUtils.isNotEmpty(request.getChronicDiseaseId())) {
            List<Long> medicalTeamIdList = docTeamDiseaseDAO.queryMedicalTeamIdList(request.getChronicDiseaseId().toString());
            request.setTeamIdList(medicalTeamIdList);
        }
        List<ChronicTeamList> list = docTeamRpcService.queryTeamList(request);
        return list;
    }

    @Override
    @RpcService
    public void applyGroupSave(GroupMemberRequest request) throws ControllerException {
        logger.info("applyGroupSave request:{}", JSON.toJSONString(request));
        String patientId = request.getPatientId();
        logger.info("patientId{}", patientId);
        if (StringUtils.isNotEmpty(patientId)) {
            if (!StringUtils.isNoneEmpty(request.getOrganizationId(),
                    request.getDoctorId(), request.getPersonId(), request.getChronicDiseaseId() + "",
                    request.getApplyPersonId(), request.getApplyPersonName(), request.getDoctorName(),
                    request.getChronicDiseaseName(), request.getOrganizationName())) {
                throw new ControllerException("入参不能为空");
            }
            FusTeamChronicGroupRecordEntity recordEntity =
                    fusTeamChronicGroupRecordDAO.getGroupRecordByDiseaseId(request.getPersonId(), request
                            .getChronicDiseaseId());
            if (recordEntity != null) {
                throw new ControllerException("该用户已有入组记录或者入组未审核记录");
            }
            DiseaseSpecies diseaseSpeciesEntity = diseaseSpeciesDAO.getDiseaseTypeDetail(request.getChronicDiseaseId());
            FusTeamChronicGroupRecordEntity record = new FusTeamChronicGroupRecordEntity();
            BeanUtils.copyProperties(request, record);
            record.setAge(request.getAge());
            record.setApplyStatus("0");
            record.setDepartmentId(diseaseSpeciesEntity.getDepartmentId());
            record.setDepartmentName(diseaseSpeciesEntity.getDepartmentName());
            record.setApplyType("1");
            record.setApplyTime(new Date());
            record.setApplyPersonId(request.getDocId());
            setOrgIdAndDeptId(record);
            fusTeamChronicGroupRecordDAO.save(record);
            return;
        } else {
            throw new ControllerException("请为该患者绑定就诊卡");
        }
//        if (!StringUtils.isNoneEmpty(request.getOrganizationId(),
//                request.getDoctorId(), request.getPersonId(), request.getChronicDiseaseId() + "",
//                request.getApplyPersonId(), request.getApplyPersonName(), request.getDoctorName(),
//                request.getChronicDiseaseName(), request.getOrganizationName())) {
//            throw new ControllerException("入参不能为空");
//        }
//        FusTeamChronicGroupRecordEntity recordEntity = fusTeamChronicGroupRecordDAO.getGroupRecordByDiseaseId(request.getPersonId(), request
//                .getChronicDiseaseId());
//        if (recordEntity != null) {
//            throw new ControllerException("该用户已有入组记录或者入组未审核记录");
//        }
//        DiseaseSpecies diseaseSpeciesEntity = diseaseSpeciesDAO.getDiseaseTypeDetail(request.getChronicDiseaseId());
//        FusTeamChronicGroupRecordEntity record = new FusTeamChronicGroupRecordEntity();
//        BeanUtils.copyProperties(request, record);
//        record.setAge(request.getAge());
//        record.setApplyStatus("0");
//        record.setDepartmentId(diseaseSpeciesEntity.getDepartmentId());
//        record.setDepartmentName(diseaseSpeciesEntity.getDepartmentName());
//        record.setApplyType("1");
//        record.setApplyTime(new Date());
//        record.setApplyPersonId(request.getDocId());
//        setOrgIdAndDeptId(record);
//        fusTeamChronicGroupRecordDAO.save(record);
//        return;
    }

    @Override
    @RpcService
    public AuditTeamGroupDetail auditTeamGroupDetail(GroupMemberRequest request) throws ControllerException {
        BaseResponse<AuditTeamGroupDetail> response = new BaseResponse<>();
        if (CommonUtils.isEmpty(request.getTeamChronicGroupId())) {
            throw new ControllerException("入参不能为空");
        }
        FusTeamChronicGroupRecordEntity entity = fusTeamChronicGroupRecordDAO.get(request.getTeamChronicGroupId());
        AuditTeamGroupDetail auditTeamGroupDetail = new AuditTeamGroupDetail();
        if (entity != null) {
            BeanUtils.copyProperties(entity, auditTeamGroupDetail);
            if (CommonUtils.isEmpty(auditTeamGroupDetail.getAge())) {
                auditTeamGroupDetail.setAge((byte) IdcardUtil.getAge(auditTeamGroupDetail.getCardNumber()));
            }
            //获取档案信息并进行封装
            PersonInfoVo personInfoVo = new PersonInfoVo();
            personInfoVo.setIdentityType(entity.getCardType());
            personInfoVo.setIdentityNo(entity.getCardNumber());
            personInfoVo.setOrgId(entity.getOrgId());
            personInfoVo.setName(entity.getPersonName());
            personInfoVo.setSex(entity.getPersonSex());
            personInfoVo.setOperationType(1);
            personInfoVo.setMpiId(entity.getPersonId());
            List<Map<String, Object>> cardManageList = cardManageService.getCardManageListByCardId(personInfoVo);
            //判断患者是否有配置诊疗卡
            if (CommonUtils.isNotEmpty(entity.getPatientMedicalCardNumber())) {
                if (CommonUtils.isNotEmpty(cardManageList)) {
                    Map<String, Object> cardManage = cardManageList.get(0);
                    List<Map<String, Object>> listMedicalCard = (List<Map<String, Object>>) cardManage.get("listMedicalCard");
                    if (CommonUtils.isNotEmpty(listMedicalCard)) {
                        for (Map<String, Object> objectMap : listMedicalCard) {
                            //若是卡号相同，patientAddress和patientNature赋值，值从HIS取
                            if (Objects.equals(objectMap.get("cardNo"), entity.getPatientMedicalCardNumber())) {
                                auditTeamGroupDetail.setAddress(CommonUtils.isEmpty(objectMap.get("patientAddress")) == true ? null : String.valueOf(objectMap.get("patientAddress")));
                                auditTeamGroupDetail.setPatientNature(String.valueOf(objectMap.get("patientNature")));
                            }
                        }
                    }
                }
            } else {
                logger.error("请为该患者办理并绑定诊疗卡");
                throw new ControllerException("请为该患者办理并绑定诊疗卡");
            }
//            if (CommonUtils.isNotEmpty(cardManageList)) {
//                Map<String, Object> cardManage = cardManageList.get(0);
//                List<Map<String, Object>> listMedicalCard = (List<Map<String, Object>>) cardManage.get("listMedicalCard");
//                if (CommonUtils.isNotEmpty(listMedicalCard)) {
//                    for (Map<String, Object> objectMap : listMedicalCard) {
//                        //若是卡号相同，patientAddress和patientNature赋值，值从HIS取
//                        if (entity.getPatientMedicalCardNumber().equals(String.valueOf(objectMap.get("cardNo")))) {
//                            auditTeamGroupDetail.setAddress(CommonUtils.isEmpty(objectMap.get("patientAddress")) == true ? null : String.valueOf(objectMap.get("patientAddress")));
//                            auditTeamGroupDetail.setPatientNature(String.valueOf(objectMap.get("patientNature")));
//                        }
//                    }
//                }
//            }
            // 查询患者已入组病种 、团队信息
            GroupMemberRequest groupMemberRequest = new GroupMemberRequest();
            groupMemberRequest.setApplyStatusQuery("1");
            groupMemberRequest.setPersonId(entity.getPersonId());
            groupMemberRequest.setDepartmentId(request.getDepartmentId());
            List<TeamChronicGroupResponse> groupResponses = fusTeamChronicGroupRecordDAO.auditGroupList(groupMemberRequest);
            if (CommonUtils.isNotEmpty(groupResponses)) {
                List<Long> teamIds = new ArrayList<>();
                for (TeamChronicGroupResponse groupResponse : groupResponses) {
                    if (CommonUtils.isNotEmpty(groupResponse.getMedicalTeamId())) {
                        teamIds.add(groupResponse.getMedicalTeamId());
                    }
                }
                if (CommonUtils.isNotEmpty(teamIds)) {
                    List<DocTeamMemberEntity> teamLeaders = docTeamMemberRpcService.queryTeamLeaderMemberListByTeamIds(teamIds);

                    Map<Long, DocTeamMemberEntity> map = new HashMap<>();
                    if (CommonUtils.isNotEmpty(teamLeaders)) {
                        for (DocTeamMemberEntity teamLeader : teamLeaders) {
                            map.put(teamLeader.getMedicalTeamId(), teamLeader);
                        }
                    }
                    List<GroupTeamInfo> chronicDiseases = new ArrayList<>();
                    for (TeamChronicGroupResponse groupResponse : groupResponses) {
                        Long chronicDiseaseId = groupResponse.getChronicDiseaseId();
                        Long teamChronicGroupId = groupResponse.getTeamChronicGroupId();

                        GroupTeamInfo groupTeamInfo = new GroupTeamInfo();
                        groupTeamInfo.setDoctorId(groupResponse.getDoctorId());
                        groupTeamInfo.setDocId(groupResponse.getDocId());
                        groupTeamInfo.setDoctorName(groupResponse.getDoctorName());
                        groupTeamInfo.setChronicDiseaseId(chronicDiseaseId);
                        groupTeamInfo.setChronicDiseaseName(groupResponse.getChronicDiseaseName());
                        groupTeamInfo.setMedicalTeamId(groupResponse.getMedicalTeamId());
                        groupTeamInfo.setMedicalTeamName(groupResponse.getMedicalTeamName());
                        groupTeamInfo.setTeamChronicGroupId(teamChronicGroupId);
                        if (CommonUtils.isNotEmpty(map.get(groupResponse.getMedicalTeamId()))) {
                            groupTeamInfo.setTeamLeaderName(map.get(groupResponse.getMedicalTeamId()).getDoctorName());
                        }
                        //根据入组id和病种id 查询已经配置的扩展属性
                        List<FusGroupChronicRecordExtendProperty> extendList = groupRecordExtendPropertyDAO.findGroupRecordExtendList(chronicDiseaseId, teamChronicGroupId);
                        groupTeamInfo.setExtendList(extendList);
                        chronicDiseases.add(groupTeamInfo);
                    }
                    if (!chronicDiseases.isEmpty()) {
                        auditTeamGroupDetail.setChronicDiseases(chronicDiseases);
                    }
                }
            }
        }
        return auditTeamGroupDetail;
    }

    @Override
    @RpcService
    public PersonGroupCountResponse personGroupCount(GroupMemberRequest request) throws ControllerException {
        BaseResponse<PersonGroupCountResponse> response = new BaseResponse<>();
        if (!StringUtils.isNoneEmpty(request.getOrganizationId(), request.getDocId())) {
            throw new ControllerException("入参不能为空");
        }
        PersonGroupCountResponse personGroupCountResponse = new PersonGroupCountResponse();
        Long myPersonCount = fusTeamChronicGroupRecordDAO.personGroupListCount(request);
        request.setDoctorId(null);
        Long allPersonCount = fusTeamChronicGroupRecordDAO.personGroupListCount(request);
        personGroupCountResponse.setMyPersonCount(myPersonCount);
        personGroupCountResponse.setAllPersonCount(allPersonCount);
        return personGroupCountResponse;
    }

    @Override
    @RpcService
    public AuditGroupCount auditGroupCount(GroupMemberRequest request) {
        AuditGroupCount auditGroupCount = new AuditGroupCount();
        //先不区分院内和院外
        // request.setApplyType("1");
        request.setApplyStatus("0");
        Long auditCount = fusTeamChronicGroupRecordDAO.auditGroupListCount(request);
        request.setApplyStatus("1");
        Long auditedCount = fusTeamChronicGroupRecordDAO.auditGroupListCount(request);
        auditGroupCount.setAuditCount(auditCount);
        auditGroupCount.setAuditedCount(auditedCount);
        return auditGroupCount;
    }

    @Override
    @RpcService
    public List<GroupTeamInfo> personGroupDetail(GroupMemberRequest request) throws ControllerException {
        if (CommonUtils.isEmpty(request.getPersonId())) {
            throw new ControllerException("入参不能为空");
        }
        // 查询患者已入组病种 、团队信息
        GroupMemberRequest groupMemberRequest = new GroupMemberRequest();
        if (CommonUtils.isEmpty(request.getApplyStatus())) {
            groupMemberRequest.setApplyStatus("1");
        } else {
            groupMemberRequest.setApplyStatus(request.getApplyStatus());
        }
        groupMemberRequest.setPersonId(request.getPersonId());

        List<TeamChronicGroupResponse> groupResponses = fusTeamChronicGroupRecordDAO.queryPatientAndDoctorGroups(groupMemberRequest);
        if (CommonUtils.isNotEmpty(groupResponses)) {
            List<Long> teamIds = new ArrayList<>();
            for (TeamChronicGroupResponse groupResponse : groupResponses) {
                if (Objects.nonNull(groupResponse.getMedicalTeamId())) {
                    teamIds.add(groupResponse.getMedicalTeamId());
                }
            }
            List<DocTeamMemberEntity> teamLeaders = docTeamMemberRpcService.queryTeamLeaderMemberListByTeamIds(teamIds);
            Map<Long, DocTeamMemberEntity> map = new HashMap<>(teamLeaders.size());
            if (CommonUtils.isNotEmpty(teamLeaders)) {
                for (DocTeamMemberEntity teamLeader : teamLeaders) {
                    map.put(teamLeader.getMedicalTeamId(), teamLeader);
                }
            }
            List<String> chronicDiseaseIds = null;
            if (StringUtils.isNotEmpty(request.getDocId())) {
                //根据当前医生信息获取teamId
                List<Long> docTeamIds = docTeamMemberRpcService.findMedicalTeamIdsByDoctorId(request.getDocId());
                chronicDiseaseIds = docTeamDiseaseDAO.findChronicDiseaseId(docTeamIds);
            }

            List<GroupTeamInfo> chronicDiseases = new ArrayList<>();
            for (TeamChronicGroupResponse groupResponse : groupResponses) {
                GroupTeamInfo groupTeamInfo = new GroupTeamInfo();
                BeanUtils.copyProperties(groupResponse, groupTeamInfo);
                if (CommonUtils.isNotEmpty(map.get(groupResponse.getMedicalTeamId()))) {
                    groupTeamInfo.setTeamLeaderName(map.get(groupResponse.getMedicalTeamId()).getDoctorName());
                }
                if (CommonUtils.isNotEmpty(chronicDiseaseIds) && groupResponse.getChronicDiseaseId() != null) {
                    if (chronicDiseaseIds.contains(groupResponse.getChronicDiseaseId().toString())) {
                        groupTeamInfo.setDocOperationFlag("1");
                    } else {
                        groupTeamInfo.setDocOperationFlag("0");
                    }
                }
                chronicDiseases.add(groupTeamInfo);
            }
            return chronicDiseases;
        }
        return null;
    }

    @Override
    @RpcService
    public List<QueryChronicListResponse> queryChronicList(GroupMemberRequest request) throws ControllerException {
        List<QueryChronicListResponse> list = new ArrayList<>();
        String roleName = RoleUtils.getCurrentCommonRole();
        if (CommonUtils.isEmpty(roleName)) {
            return list;
        }
        if (CommonUtils.isEmpty(request.getDocId())) {
            throw new ControllerException("入参不能为空");
        }
        if (CommonUtils.isEmpty(request.getPersonId())) {
            GroupMemberRequest groupMemberRequest = new GroupMemberRequest();
            groupMemberRequest.setDocId(request.getDocId());
            List<ChronicTeamList> chronicTeamLists = docTeamRpcService.queryTeamList(groupMemberRequest);
            if (CommonUtils.isNotEmpty(chronicTeamLists)) {
                List<Long> collect = chronicTeamLists.stream().map(c -> c.getMedicalTeamId()).collect(Collectors.toList());
                //通过医生Id查询病种
                list = fusTeamChronicGroupRecordDAO.queryChronicList(collect);
            }

        } else {
            //通过患者Id查询病种
            list = fusTeamChronicGroupRecordDAO.queryChronicListByPersonId(request.getPersonId());
        }
        return list;
    }

    @Override
    @RpcService
    public List<QueryChronicDoctorListResponse> queryChronicDoctorList(GroupMemberRequest request) throws ControllerException {
        if (CommonUtils.isEmpty(request.getDocId()) || CommonUtils.isEmpty(request.getChronicDiseaseId())) {
            throw new ControllerException("入参不能为空");
        }

        List<Long> medicalTeamIdList = docTeamDiseaseDAO.queryMedicalTeamIdList(request.getChronicDiseaseId().toString());
        if (CommonUtils.isNotEmpty(medicalTeamIdList)) {
            List<QueryChronicDoctorListResponse> list = docTeamMemberRpcService.queryChronicDoctorList(request.getDocId(), medicalTeamIdList);
            return list;
        }
        return null;
    }

    @Override
    @RpcService
    public List<DiseaseExtendPropertyResponse> queryChronicExtendPropertyList(GroupMemberRequest request) throws ControllerException {
        if (CommonUtils.isEmpty(request.getChronicDiseaseId())) {
            throw new ControllerException("入参不能为空");
        }
        //先筛选属性名称
        List<DiseaseExtendPropertyResponse> responseList = new ArrayList<>();
        List<DiseaseExtendPropertyEntity> firstList = diseaseExtendPropertyDAO.queryFirstDiseaseByDiseaseTypeId(request.getChronicDiseaseId());
        if (CommonUtils.isNotEmpty(firstList)) {
            //筛选属性值
            for (DiseaseExtendPropertyEntity diseaseExtendPropertyEntity : firstList) {
                DiseaseExtendPropertyResponse diseaseExtendPropertyResponse = new DiseaseExtendPropertyResponse();
                BeanUtils.copyProperties(diseaseExtendPropertyEntity, diseaseExtendPropertyResponse);
                List<DiseaseExtendPropertyEntity> secondList = diseaseExtendPropertyDAO.querySecondDiseaseByDiseaseTypeId(diseaseExtendPropertyEntity.getDiseaseTypeId(), diseaseExtendPropertyEntity.getExtendId());
                diseaseExtendPropertyResponse.setDiseaseList(secondList);
                responseList.add(diseaseExtendPropertyResponse);
            }
        }
        return responseList;
    }

    @Override
    @RpcService
    public List<QueryDoctorDepartmentListResponse> queryDoctorDepartmentList(GroupMemberRequest request) throws ControllerException {
        if (CommonUtils.isEmpty(request.getDocId())) {
            throw new ControllerException("入参不能为空");
        }
        List<QueryDoctorDepartmentListResponse> list = docTeamRpcService.queryDoctorDepartmentList(request.getDocId());
        return list;
    }

    public void autoFollowUpRecords() {


    }

    /**
     * 通过证件号获取用户慢病宣教列表
     *
     * @param queryDiseasesAndFusListResp
     */
    @Override
    public List<DiseasesAndFusListResponse> queryDiseasesAndFusList(QueryDiseasesAndFusListResp queryDiseasesAndFusListResp) throws ControllerException {
        List<DiseasesAndFusListResponse> responseList = new ArrayList<>();
        //获取用户慢病list
        List<FusTeamChronicGroupRecordEntity> fusRecordsBycardNumberList = fusTeamChronicGroupRecordDAO.findFusRecordsBycardNumber(queryDiseasesAndFusListResp.getCardType(), queryDiseasesAndFusListResp.getCardNumber());

        List<Long> chronicDiseaseIdList = new ArrayList<>();
        //判断list是否为空
        if (CommonUtils.isNotEmpty(fusRecordsBycardNumberList)) {
            for (FusTeamChronicGroupRecordEntity fusTeamChronicGroupRecordEntity : fusRecordsBycardNumberList) {
                chronicDiseaseIdList.add(fusTeamChronicGroupRecordEntity.getChronicDiseaseId());
            }
            //根据慢病id查病健康宣教列表
            List<HealthEducationList> findDiseaseTypeList = fusHealthEducationService.findDiseaseTypeListByDiseeIdarr(chronicDiseaseIdList);
            if (CommonUtils.isNotEmpty(findDiseaseTypeList)) {
                //遍历新的宣教列表
                for (HealthEducationList healthEducationList : findDiseaseTypeList) {
                    DiseasesAndFusListResponse diseasesAndFusListResponse = new DiseasesAndFusListResponse();
                    diseasesAndFusListResponse.setEducationId(healthEducationList.getFusHealthEducationId());
                    diseasesAndFusListResponse.setEducationName(healthEducationList.getName());

                    //获取病种列表
                    List<FusHealthEducationRelation> fusHealthEducationRelations = fusHealthEducationService.findFusHealthEducationRelations(Long.parseLong(healthEducationList.getFusHealthEducationId()));

                    diseasesAndFusListResponse.setFusHealthEducationRelationLists(fusHealthEducationRelations);
                    responseList.add(diseasesAndFusListResponse);
                }
            }

        } else {
            throw new ControllerException("未查询到用户入组信息！");
        }
        return responseList;
    }

    @Override
    @RpcService
    public List<Long> queryDiseaseIdByPersonId(String personId) {
        if (CommonUtils.isEmpty(personId)) {
            return Collections.emptyList();
        }
        return fusTeamChronicGroupRecordDAO.findChronicDiseaseIdByPersonId(personId);
    }

    /**
     * 获取病种信息列表根据当前登录医生和患者id
     *
     * @param request
     * @return
     */
    @Override
    @RpcService
    public List<TeamChronicGroupResponse> queryChronicGroupList(GroupMemberRequest request) throws ControllerException {
        if (CommonUtils.isEmpty(request.getDocId())) {
            //从当前登录人获取
            UserAllVo user = baseDeviceService.getAllByOnline();
            if (Objects.nonNull(user) && StringUtils.isNotEmpty(user.getLocalDoctorId())) {
                request.setDocId(user.getLocalDoctorId());
            } else {
                throw new ControllerException("医生id不可为空");
            }

        }
        if (CommonUtils.isEmpty(request.getPersonId())) {
            throw new ControllerException("患者id不可为空");
        }
        //根据当前医生信息获取teamId
        List<Long> teamIds = docTeamMemberRpcService.findMedicalTeamIdsByDoctorId(request.getDocId());


        //获取病种信息 -----新需求 查询该患者的所有入组记录对应的病种 不关联医生信息
        //有效病种
        if (CommonUtils.isEmpty(request.getApplyStatus())){
            request.setApplyStatus("1");
        }
        List<TeamChronicGroupResponse> teamChronicGroupList = fusTeamChronicGroupRecordDAO.auditGroupMemberList(request, null);
        //适配国产化，根据PersonId去重
        if (CommonUtils.isNotEmpty(teamChronicGroupList)) {
            List<TeamChronicGroupResponse> newList = teamChronicGroupList.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TeamChronicGroupResponse::getChronicDiseaseId))), ArrayList::new));
            List<TeamChronicGroupResponse> removeList = new ArrayList<>();
            newList.forEach(data -> {
                if (Objects.equals(data.getApplyStatus(),"2")) {
                    removeList.add(data);
                }
            });
            newList.removeAll(removeList);
            teamChronicGroupList = newList;

            if (CommonUtils.isNotEmpty(teamChronicGroupList) && CommonUtils.isNotEmpty(teamIds)) {
                //查出当前医生管理的团队的所有病种
                final List<String> chronicDiseaseIds = docTeamDiseaseDAO.findChronicDiseaseId(teamIds);
                teamChronicGroupList.stream().forEach(g -> {
                    if (chronicDiseaseIds.contains(g.getChronicDiseaseId().toString())) {
                        g.setDocOperationFlag("1");
                    } else {
                        g.setDocOperationFlag("0");
                    }

                });
            }


        }


        return teamChronicGroupList;
    }


    /**
     * @Author:FangZhiYi
     * @Description 医生站入组url  加密参数解密
     * @Params [request]
     * @Return java.lang.String
     * @Data Created in 2021/12/16 16:35
     * @Moddified By:
     */
    @Override
    @RpcService
    public String decryptData(@RequestBody DecryptDataReq request) throws ControllerException {
        if (CommonUtils.isNotEmpty(request.getData())) {
            logger.info("TeamChronicGroupService.decryptData：{}", request);
            try {
                String decode = URLDecoder.decode(request.getData().replace("+", "%2b"), "UTF-8");
                String s = SM4Utils.decryptData_ECB(decode);
                String plainText = new String(Base64.decodeBase64(s.getBytes("UTF-8")), "UTF-8");
                logger.info("解密结果Base64之后: " + plainText);
                JSONObject result = JSON.parseObject(plainText);
                if (StringUtils.isNotEmpty(result.getString("organizationId")) && StringUtils.isNotEmpty(result.getString("doctorId"))) {
                    Map<String, Object> docInfo = doctorInfoServiceIntf.getDocInfoByLocalDoctorId(result.getString("organizationId"), result.getString("doctorId"));
                    if (CommonUtils.isNotEmpty(docInfo)) {
                        result.put("docId", docInfo.get("doctorId").toString());
                        String userId = docInfo.get("userId").toString();
                        String deptId = docInfo.get("deptId").toString();
                        String accessToken = userService.getTokenByUserId(userId, deptId);
                        result.put("token", accessToken);
                    }
                } else {
                    throw new ControllerException("解密后机构或医生编码为空");
                }
                return result.toJSONString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                throw new ControllerException("解密报错：" + e.getMessage());
            }
        }
        return null;
    }

    @Override
    @RpcService
    public String encryptData(@RequestBody DecryptDataReq request) throws ControllerException {
        if (CommonUtils.isNotEmpty(request.getData())) {
            logger.info("TeamChronicGroupService.encryptData：{}", request);
            try {
                String plainText = new String(Base64.encodeBase64(request.getData().getBytes("UTF-8")));
                String result = SM4Utils.encryptData_ECB(plainText);
                result = URLEncoder.encode(result, "UTF-8");
                logger.info("加密结果Encoder之后: " + result);
                return result;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                throw new ControllerException("加密报错：" + e.getMessage());
            }
        }
        return null;
    }

    /**
     * 查询当前患者是否有待确认的入组信息
     */
    @Override
    public AuditGroupCount getToConfirmedGroupCount(GroupMemberRequest request) throws ControllerException {

        if (StringUtils.isEmpty(request.getCardNumber()) || StringUtils.isEmpty(request.getCardType())) {
            throw new ControllerException("用户信息不能为空！");
        }
        return fusTeamChronicGroupRecordDAO.getToConfirmedGroupCount(request);
    }


    /**
     * 查询当前患者是否有待确认的入组信息列表
     */
    @Override
    public List<FusTeamChronicGroupRecordEntity> queryToConfirmedGroup(GroupMemberRequest request) throws ControllerException {

        if (StringUtils.isEmpty(request.getCardNumber()) || StringUtils.isEmpty(request.getCardType())) {
            throw new ControllerException("用户信息不能为空！");
        }
        return fusTeamChronicGroupRecordDAO.queryToConfirmedGroup(request);
    }

    /**
     * 患者保存 确认入组协议
     */
    @Override
    public void saveConfirmedGroup(FusTeamChronicGroupRecordEntity request) throws ControllerException {

        if (CommonUtils.isEmpty(request.getTeamChronicGroupId())) {
            throw new ControllerException("入组主键id不存在");
        }
        if (StringUtils.isEmpty(request.getProtocolStatus()) || StringUtils.isEmpty(request.getProtocolPersonId()) || StringUtils.isEmpty(request.getProtocolPersonName())) {
            throw new ControllerException("患者的确认状态信息有缺少");
        }
        if ("1".equals(request.getProtocolStatus())) {
            //患者确认入组成功
            request.setApplyStatus("1");
        } else if ("2".equals(request.getProtocolStatus())) {
            request.setApplyStatus("2");
        } else {
            throw new ControllerException("患者的确认状态不识别！");
        }
        fusTeamChronicGroupRecordDAO.updateProtocol(request);

        FusTeamChronicGroupRecordEntity entity = fusTeamChronicGroupRecordDAO.get(request.getTeamChronicGroupId());

        if (CommonUtils.isEmpty(entity)) {
            throw new ControllerException("当前入组信息不存在");
        }
        //修改高级搜索的患者入组病种记录
        if (StringUtils.isNotEmpty(entity.getCardNumber())) {
            List<PatientSearchResult> patientSearchResults = patientSearchResultDAO.queryPatientSearchResultByCardNumber(entity.getCardNumber());
            if (CommonUtils.isNotEmpty(patientSearchResults)) {
                patientSearchResults.stream().forEach(patientSearchResult -> {
                    if (StringUtils.isEmpty(patientSearchResult.getChronicDiseaseName())) {
                        patientSearchResult.setChronicDiseaseIds(entity.getChronicDiseaseId() + "");
                        patientSearchResult.setChronicDiseaseName(entity.getChronicDiseaseName());
                    } else if (!patientSearchResult.getChronicDiseaseName().contains(entity.getChronicDiseaseName())) {
                        patientSearchResult.setChronicDiseaseIds(patientSearchResult.getChronicDiseaseIds() + "," + entity.getChronicDiseaseId());
                        patientSearchResult.setChronicDiseaseName(patientSearchResult.getChronicDiseaseName() + "," + entity.getChronicDiseaseName());
                    }
                    patientSearchResult.setOrganizationId(entity.getOrganizationId());
                    patientSearchResultDAO.update(patientSearchResult);
                });
            }
        }
    }
}
